package LeetCodeHot100TopInterview;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Q103_ZigzagLevelOrder {

    //之字形打印二叉树
    //层序遍历的变种
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {

        if (root == null){
            return new LinkedList<>();
        }
        List<List<Integer>> ans = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        boolean style = false;
        queue.add(root);
        //true正 false 反

        int size = 0;
        while (queue.size() != 0){
            LinkedList<Integer> tmp = new LinkedList<>();
            style = !style;
            size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (style){
                    tmp.addLast(poll.val);
                }else {
                    tmp.addFirst(poll.val);
                }
                if (poll.left != null){
                    queue.add(poll.left);
                }
                if (poll.right != null){
                    queue.add(poll.right);
                }
            }
            ans.add(tmp);
        }
        return ans;
    }


}
